package com.example.zz.example;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.Rect;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.elvishew.xlog.XLog;
import com.example.zz.example.H5.H5AndroidActivity;
import com.example.zz.example.animations.AnimationsActivity;
import com.example.zz.example.anr.AnrActivity;
import com.example.zz.example.badgecount.BadgeCountActivity;
import com.example.zz.example.broadcast.BroadcastActivity;
import com.example.zz.example.clickevent.ClickEventActivity;
import com.example.zz.example.clickspanner.WeiboContentTestActivity;
import com.example.zz.example.customcontrol.CustomControlActivity;
import com.example.zz.example.databinding.DatabindTestActivity;
import com.example.zz.example.extractorvideo.MediaExtractorActivity;
import com.example.zz.example.fileproviderandshare.FileProviderAndShareActivity;
import com.example.zz.example.game.PlaneGameActivity;
import com.example.zz.example.handler.HandlerActivity;
import com.example.zz.example.java.annotation.AnnotationActivity;
import com.example.zz.example.mediaplayer.AidlActivity;
import com.example.zz.example.mediaplayer.ZzPlayerActivity;
import com.example.zz.example.mediarecorder.MediaActivity;
import com.example.zz.example.memory.MemoryActivity;
import com.example.zz.example.memorylink.MemoryLinkActivity;
import com.example.zz.example.network.HomeActivity;
import com.example.zz.example.network.NetWorkActivity;
import com.example.zz.example.network.bean.MainBean;
import com.example.zz.example.pattern.PatternActivity;
import com.example.zz.example.pattern.rxjava.RxjavaActivity;
import com.example.zz.example.pictureload.PictureLoadActivity;
import com.example.zz.example.reflection.ReflectionActivity;
import com.example.zz.example.shape.ShapeActivity;
import com.example.zz.example.storage.FileStorageTestActivity;
import com.example.zz.example.timer.TimerActivity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity implements MainRecyclerViewAdapter.OnItemClickListener {

    private ArrayList<MainBean> mainBeansList;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getDeviceInfo();
        initPermission();
        initData();
        getNewShortcutInfo();
        setAdapter();
    }

    private void initData() {
        mainBeansList = new ArrayList<>();
        mainBeansList.add(new MainBean(this, "shape图形汇总", ShapeActivity.class));
        mainBeansList.add(new MainBean(this, "进入存储检测", MemoryActivity.class));
        mainBeansList.add(new MainBean(this, "进入数据库", DatabaseActivity.class));
        mainBeansList.add(new MainBean(this, "进入游戏界面", PlaneGameActivity.class));
        mainBeansList.add(new MainBean(this, "ClickEvent", ClickEventActivity.class));
        mainBeansList.add(new MainBean(this, "多媒体，音乐，视频，aidl", AidlActivity.class));
        mainBeansList.add(new MainBean(this, "内存泄漏", MemoryLinkActivity.class));
        mainBeansList.add(new MainBean(this, "ANR", AnrActivity.class));
        mainBeansList.add(new MainBean(this, "RecyclerView测试", HomeActivity.class));
        mainBeansList.add(new MainBean(this, "富文本", WeiboContentTestActivity.class));
        mainBeansList.add(new MainBean(this, "自定义控件", CustomControlActivity.class));
        mainBeansList.add(new MainBean(this, "设计模式", PatternActivity.class));
        mainBeansList.add(new MainBean(this, "handler", HandlerActivity.class));
        mainBeansList.add(new MainBean(this, "图片加载", PictureLoadActivity.class));
        mainBeansList.add(new MainBean(this, "剪映", MediaExtractorActivity.class));
        mainBeansList.add(new MainBean(this, "zzplayer 视频播放器", ZzPlayerActivity.class));
        mainBeansList.add(new MainBean(this, "录屏、截屏、录像、拍照", MediaActivity.class));
        mainBeansList.add(new MainBean(this, "广播与本地广播", BroadcastActivity.class));
        mainBeansList.add(new MainBean(this, "RxJava", RxjavaActivity.class));
        mainBeansList.add(new MainBean(this, "Dagger2+Retrofit2+Rxjava2", NetWorkActivity.class));
        mainBeansList.add(new MainBean(this, "反射", ReflectionActivity.class));
        mainBeansList.add(new MainBean(this, "注解", AnnotationActivity.class));
        mainBeansList.add(new MainBean(this, "计数器", TimerActivity.class));
        mainBeansList.add(new MainBean(this, "H5互交", H5AndroidActivity.class));
        mainBeansList.add(new MainBean(this, "fileprovider获取uri并分享", FileProviderAndShareActivity.class));
        mainBeansList.add(new MainBean(this, "分区存储、多媒体文件操作", FileStorageTestActivity.class));
        mainBeansList.add(new MainBean(this, "databing使用", DatabindTestActivity.class));
        mainBeansList.add(new MainBean(this, "角标使用", BadgeCountActivity.class));
        mainBeansList.add(new MainBean(this, "字体风格", TextStyleActivity.class));
        mainBeansList.add(new MainBean(this, "简单动画", AnimationsActivity.class));
    }

    private void setAdapter() {
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        // 1.设置LayoutManager
        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
        manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(manager);

        // 2.添加ItemDecoration
        // 每个item之间的间距
        int divider = -4;
        RecyclerView.ItemDecoration gridItemDecoration = new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, RecyclerView parent, @NonNull RecyclerView.State state) {
                StaggeredGridLayoutManager.LayoutParams layoutParams = (StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams();
                int spanIndex = layoutParams.getSpanIndex();
                int position = parent.getChildAdapterPosition(view);
                outRect.top = divider;
                outRect.bottom = divider;
                outRect.left = divider;
                outRect.right = divider;
//                if (position == 0 || position == 1) {
//                    outRect.top = divider * 2;
//                } else {
//                    outRect.top = 0;
//                }
//                if (spanIndex % 2 == 0) {//偶数项
//                    outRect.left = divider;
//                    outRect.right = divider / 2;
//                } else {
//                    outRect.left = divider / 2;
//                    outRect.right = divider;
//                }
            }
        };
        recyclerView.addItemDecoration(gridItemDecoration);
        MainRecyclerViewAdapter mainRecyclerViewAdapter = new MainRecyclerViewAdapter();
        recyclerView.setAdapter(mainRecyclerViewAdapter);
        mainRecyclerViewAdapter.updateData(mainBeansList);
        mainRecyclerViewAdapter.setOnItemClickListener(this);
    }


    private void getDeviceInfo() {
        String handSetInfo = "手机型号:" + Build.MODEL
                + "\n系统版本:" + Build.VERSION.RELEASE
                + "\n产品型号:" + Build.PRODUCT
                + "\n版本显示:" + Build.DISPLAY
                + "\n系统定制商:" + Build.BRAND
                + "\n设备参数:" + Build.DEVICE
                + "\n开发代号:" + Build.VERSION.CODENAME
                + "\nSDK版本号:" + Build.VERSION.SDK_INT
                + "\nCPU类型:" + Build.CPU_ABI
                + "\n硬件类型:" + Build.HARDWARE
                + "\n主机:" + Build.HOST
                + "\n生产ID:" + Build.ID
                + "\nROM制造商:" + Build.MANUFACTURER // 这行返回的是rom定制商的名称
                ;
        XLog.i(handSetInfo);
    }


    /**
     * 添加shotcut功能：桌面图标长按后弹出快捷入口，支持弹框将界面设置为快捷入口
     * https://www.jianshu.com/p/68429e6c73ae
     */
    private void getNewShortcutInfo() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
            return;
        }

        // 系统提供的
        ShortcutManager mShortcutManager = getSystemService(ShortcutManager.class);

        // 按下返回按钮跳转的activity
        Intent intent1 = new Intent(this, MainActivity.class);
        intent1.setAction(Intent.ACTION_VIEW);
        // 目标activity
        Intent intent2 = new Intent(this, MemoryActivity.class);
        intent2.setAction("com.shark.xxx.BACK");
        Intent[] intents = new Intent[2];
        intents[0] = intent1;
        intents[1] = intent2;

        // 一个具体的快捷对象
        ShortcutInfo shortcut = new ShortcutInfo.Builder(this, "id1") // id 标识是唯一的
                .setShortLabel("内存扫描_快捷入口")  // 桌面快捷方式显示的名字
                .setLongLabel("内存扫描")      // 长按弹窗显示的名字
                .setIcon(Icon.createWithResource(this, R.drawable.die))  // 显示的Icon
                .setIntents(intents) // 意图设置
                .build(); // 构建

        ShortcutInfo shortcut2 = new ShortcutInfo.Builder(this, "id2")
                .setShortLabel("hao123_快捷入口")
                .setLongLabel("hao123")
                .setIcon(Icon.createWithResource(this, R.drawable.die))
                .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.hao123.com/")))
                .build();

        ShortcutInfo shortcut3 = new ShortcutInfo.Builder(this, "id3")
                .setShortLabel("github")
                .setLongLabel("github")
                .setIcon(Icon.createWithResource(this, R.drawable.die))
                .setIntent(new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.github.com/")))
                .build();

        // 创建长按快捷键，调用后，在桌面长按图标会弹出快速进入入口
        mShortcutManager.setDynamicShortcuts(Arrays.asList(shortcut, shortcut2, shortcut3));

        // 创建桌面快捷键，调用后，会马上弹框提示为下面的intent创建桌面入口
//        PendingIntent successCallback = PendingIntent.getBroadcast(this, 0, mShortcutManager.createShortcutResultIntent(shortcut), 0);
//        mShortcutManager.requestPinShortcut(shortcut,successCallback.getIntentSender());
    }

    /**
     * 动态删除
     */
    public void delete() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
            return;
        }
        ShortcutManager mShortcutManager = getSystemService(ShortcutManager.class);

        /********* 移除弹出列表图标 **********/
        // 所有动态创建图标
        List<ShortcutInfo> infos1 = mShortcutManager.getDynamicShortcuts();

        List<String> ids1 = new ArrayList<>();
        for (ShortcutInfo info : infos1) {
            ids1.add(info.getId());
        }

        // 禁用所有的快捷方式
        mShortcutManager.disableShortcuts(ids1, "已禁用");
        mShortcutManager.removeDynamicShortcuts(ids1);

        /********* 移除拖出来的桌面快捷图标 **********/
        // 放在桌面的图标
        List<ShortcutInfo> infos2 = mShortcutManager.getPinnedShortcuts();

        List<String> ids2 = new ArrayList<>();
        for (ShortcutInfo info : infos2) {
            ids2.add(info.getId());
        }

        mShortcutManager.disableShortcuts(ids2, "已禁用");
        mShortcutManager.removeAllDynamicShortcuts();
    }


    private void initPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            List<String> mPermissionList = new ArrayList<>();
            String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.INTERNET};
            //逐个判断你要的权限是否已经通过
            for (int i = 0; i < permissions.length; i++) {
                if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permissions[i]);//添加还未授予的权限
                }
            }
            //申请权限
            if (mPermissionList.size() > 0) {
                //有权限没有通过，需要申请
                ActivityCompat.requestPermissions(this, permissions, 500);
            } else {
                //说明权限都已经通过，可以做你想做的事情去
            }
        }
    }


    @Override
    public void onItemClick(int position) {
        mainBeansList.get(position).goToActivity();

    }
}
